package com.wootion.cims.general.timetask;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wootion.cims.dao.PersonDao;
import com.wootion.cims.dao.UserDao;
import com.wootion.cims.general.utils.IdChack;
import com.wootion.cims.module.communitypersonal.model.Person;
import com.wootion.cims.module.systemsetting.user.model.User;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Configuration
@EnableScheduling
public class TimeTask {

    @Resource
    PersonDao personDao;

    @Resource
    UserDao userDao;

    /**
     * 每日凌晨更新年龄
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(fixedDelay = 86400000L)
//    @Scheduled(fixedDelay = 50000000L)
    public void chageAge() throws ParseException {
        Calendar c=Calendar.getInstance();
        log.info("开始了定时任务");
        QueryWrapper<Person> queryWrapper = new QueryWrapper();
        queryWrapper.eq("enabled",true);
        List<Person> people = personDao.selectList(queryWrapper);
        for (Person person : people){
            String idNumber = person.getIdNumber();
            if (idNumber.equals("131025202212091250")){
                System.out.println("a");
            }

            JSONObject jsonObject = IdChack.IDcard(idNumber);
            if (Optional.ofNullable(jsonObject).isPresent()){
                Date date = new Date();
                String bris = jsonObject.getString("year")+jsonObject.getString("month")+jsonObject.getString("day");
                Integer brii = Integer.valueOf(bris);

                int i = c.get(Calendar.YEAR);
                int i1 = c.get(Calendar.MONTH);
                int i2 = c.get(Calendar.DATE);
                String is = String.valueOf(i);
                String i1s = String.valueOf(++i1);
                String i2s = String.valueOf(i2);
                if (i1<10){
                    i1s = "0"+i1;
                }
                if (i2<10){
                    i2s = "0"+i2;
                }
                String nows = is + i1s + i2s;
                Integer nowi = Integer.valueOf(nows);
                Integer age = (nowi-brii)/10000;

                if (age == 0){
                    SimpleDateFormat bDate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//创建日期格式化
                    String format = bDate.format(new Date());
                    String format2 = bDate.format(person.getBirthTime());
                    String s = yearCompare(format2, format);
                    person.setAge(s);
//                    long a=bDate.parse(String.valueOf(brii)).getTime();
//                    long time = new Date().getTime();
//                    long l = time - a;
//                    long l1 = l / 1000 / 60 / 60 / 24 /30;
////                    Integer str = (nowi-brii)/100;
//                    if (l1 == 0 || l1 == 1){
//                        person.setAge(1+"个月");
//                    }
                }else {
                    person.setAge(String.valueOf(age));
                }

                System.out.println(person.getName()+"当前时间为"+nowi+",读取时间为"+brii);
                if(age >= 60){
                    person.setOldmanInset("true");
                    String oldman = person.getOldman();
                    JSONObject jsonObject1 = JSONObject.parseObject(oldman);
                    jsonObject1.put("enable",true);
                    String string = jsonObject1.toJSONString();
                    person.setOldman(string);
                }
                personDao.updateById(person);
            }else {
                log.debug("身份证号为"+idNumber+"的信息不合法");
            }
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper();
        userQueryWrapper.eq("enabled",true);
        List<User> users = userDao.selectList(userQueryWrapper);
        for (User user : users) {

            Date endTime = user.getEndTime();
            if (Optional.ofNullable(endTime).isPresent()) {
                long time2 = endTime.getTime();
                time2+=86400000;
                Calendar instance = Calendar.getInstance();
                Date time = instance.getTime();
                long time1 = time.getTime();
                if (time1 > time2 && user.getUseTime().equals("临时")) {
                    user.setAccount("已停用");
                    userDao.updateById(user);
                }
            }
        }
    }

    public String yearCompare(String fromDateString/*1988-10-24 00:00:00*/, String toDateString/*2022-02-26 15:10:44*/){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date fromDate = null;
        Date toDate = null;
        try {
            fromDate = format.parse(fromDateString);
            toDate = format.parse(toDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);

        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);
        int fromDay = from.get(Calendar.DAY_OF_MONTH);

        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        int toDay = to.get(Calendar.DAY_OF_MONTH);
        int year = toYear  -  fromYear;
        int month = toMonth  - fromMonth;
        int day = toDay  - fromDay;

        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        Calendar now = Calendar.getInstance();
        if (day <0) {
            month -=1;

            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。

            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);

        }

        if (month <0) {
            month = (month +12) %12;

            year--;

        }


        StringBuffer age =new StringBuffer();
//        String s = "";

//        if (year >0) {
//            age.append(year +"岁");
//
//        }

        if (month >0) {
            age.append(month +"个月");

        }else if (day >0) {
            age.append("1个月");

        }else if (year ==0 && month ==0 && day ==0) {
            age.append("1个月");

        }

        return String.valueOf(age);
    }
}
//package com.wootion.cims.general.timetask;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.wootion.cims.dao.PersonDao;
//import com.wootion.cims.general.utils.IdChack;
//import com.wootion.cims.module.communitypersonal.model.Person;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//
//import javax.annotation.Resource;
//import java.time.LocalDateTime;
//import java.util.Calendar;
//import java.util.Date;
//import java.util.List;
//import java.util.Optional;
//
//@Slf4j
//@Configuration
////@EnableScheduling
//public class TimeTask {
//
//    static Calendar c=Calendar.getInstance();
//
//    @Resource
//    PersonDao personDao;
//
//    /**
//     * 每日凌晨更新年龄
//     */
//    @Scheduled(cron = "0 0 1 * * ?")
//    //@Scheduled(cron = "*/5 * * * * ?")
//    public void chageAge(){
//        QueryWrapper<Person> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("enabled",true);
//        List<Person> people = personDao.selectList(queryWrapper);
//        for (Person person : people){
//            String idNumber = person.getIdNumber();
////            if (idNumber.equals("312019196301301531")){
////                System.out.println("a");
////            }
//            JSONObject jsonObject = IdChack.IDcard(idNumber);
//            if (Optional.ofNullable(jsonObject).isPresent()){
//                Date date = new Date();
//                String bris = jsonObject.getString("year")+jsonObject.getString("month")+jsonObject.getString("day");
//                Integer brii = Integer.valueOf(bris);
//
//                int i = c.get(Calendar.YEAR);
//                int i1 = c.get(Calendar.MONTH);
//                int i2 = c.get(Calendar.DATE);
//                String is = String.valueOf(i);
//                String i1s = String.valueOf(i1);
//                String i2s = String.valueOf(i2);
//                if (i1<10){
//                    i1s = "0"+i1;
//                }
//                if (i2<10){
//                    i2s = "0"+i2;
//                }
//                String nows = is + i1s + i2s;
//                Integer nowi = Integer.valueOf(nows);
//                Integer age = (nowi-brii)/10000;
//
//                if(age > 60){
//                    person.setOldmanInset("1");
//                }
//                person.setAge(String.valueOf(age));
//                personDao.updateById(person);
//            }else {
//                log.debug("身份证号为"+idNumber+"的信息不合法");
//            }
//        }
//
//    }
//}





